package org.jeecg.modules.dock.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.api.controller.SystemApiController;
import org.jeecg.modules.basic.customer.entity.BasicCustomer;
import org.jeecg.modules.basic.customer.service.IBasicCustomerService;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfo;
import org.jeecg.modules.basic.material.mapper.WmsBasicMaterialStockInfoMapper;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.print.service.IWmsDocumentTypeStatusService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseArea;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaService;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptService;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.mapper.WmsOutReceiptTaskMaterialMapper;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskMaterialService;
import org.jeecg.modules.business.outbound.service.impl.WmsOutReceiptTaskServiceImpl;
import org.jeecg.modules.business.outbound.vo.WmsOutReceiptTaskPage;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.mapper.WmsRepertoryMapper;
import org.jeecg.modules.business.repertory.service.impl.WmsRepertoryServiceImpl;
import org.jeecg.modules.business.strategy.service.IMesSiteService;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceipt;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceiptMaterial;
import org.jeecg.modules.business.transfer.mapper.WmsMoveReceiptMapper;
import org.jeecg.modules.business.transfer.vo.WmsMoveReceiptPage;
import org.jeecg.modules.business.warehouse.entity.InspectResultEnum;
import org.jeecg.modules.business.warehouse.entity.InspectStatusEnum;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTaskMaterial;
import org.jeecg.modules.business.warehouse.entity.vo.WmsInReceiptTaskPage;
import org.jeecg.modules.business.warehouse.mapper.WmsInReceiptTaskMaterialMapper;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskMaterialService;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskService;
import org.jeecg.modules.dock.client.MdsRequestClient;
import org.jeecg.modules.dock.client.MesRequestClient;
import org.jeecg.modules.dock.config.JsonUtils;
import org.jeecg.modules.dock.constant.DocumentTask;
import org.jeecg.modules.dock.constant.OutboundTask;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.entity.DockDataReceiveRecord;
import org.jeecg.modules.dock.entity.DockDataSendRecord;
import org.jeecg.modules.dock.entity.DockTaskRecordMap;
import org.jeecg.modules.dock.entity.WmsWarehousePaperConfig;
import org.jeecg.modules.dock.entity.dto.request.BaseRequestDTO;
import org.jeecg.modules.dock.entity.ems.response.EmsBaseResponseVO;
import org.jeecg.modules.dock.entity.mds.MdsBaseResponseVO;
import org.jeecg.modules.dock.entity.mds.request.ForceCompleteRequestVO;
import org.jeecg.modules.dock.entity.mds.request.MDSCrossCutTheScrapBinRequestVO;
import org.jeecg.modules.dock.entity.mds.request.MDSLaminationAndRefeedingRequestVO;
import org.jeecg.modules.dock.entity.mds.request.MDSTheTransverseShearIsCalledAScrapBinRequestVO;
import org.jeecg.modules.dock.entity.mes.request.*;
import org.jeecg.modules.dock.entity.mes.response.MesBaseResponseVO;
import org.jeecg.modules.dock.enums.*;
import org.jeecg.modules.dock.mapper.DockDataSendRecordMapper;
import org.jeecg.modules.dock.mapper.DockTaskRecordMapMapper;
import org.jeecg.modules.dock.mapper.WmsWarehousePaperConfigMapper;
import org.jeecg.modules.dock.service.EmsDockingRepeaterService;
import org.jeecg.modules.dock.service.MdsDockingRepeaterService;
import org.jeecg.modules.dock.service.MesDockingRepeaterService;
import org.jeecg.modules.dock.service.MesDockingService;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * mes对接数据服务
 *
 * @author zhoutong
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MesDockingServiceImpl implements MesDockingService {

    private static final String WAREHOUSE_DOCUMENT_CODE = "rkrw_rule";
    private static final String WAREHOUSE_PARAM = "{\"prefix\":\"RKRW\"}";
    private static final String OUTBOUND_DOCUMENT_CODE = "ckrw_rule";
    private static final String OUTBOUND_PARAM = "{\"prefix\":\"CKRW\"}";
    private static final String MOVE_DOCUMENT_CODE = "yk_rule";
    private static final String MOVE_PARAM = "{\"prefix\":\"YK\"}";
    private static final String MOVE_Y14 = "Y14";
    final String DOCUMENT_TASK = "document_task";
    final String OUTBOUND_TASK = "outbound_task";
    private final WmsOutReceiptTaskServiceImpl outReceiptTaskService;
    private final SystemApiController systemApiController;
    private final WmsRepertoryServiceImpl repertoryService;
    private final IWmsInReceiptTaskService iWmsInReceiptTaskService;
    private final WorkFlowService workFlowService;
    private final MesRequestClient mesRequestClient;
    private final EmsDockingRepeaterService emsDockingRepeaterService;
    private final DockTaskRecordMapMapper dockTaskRecordMapMapper;
    private final MdsRequestClient mdsRequestClient;
    private final DockDataSendRecordMapper dockDataSendRecordMapper;
    private final MdsDockingRepeaterService mdsDockingRepeaterService;
    private final IWmsDocumentTypeStatusService wmsDocumentTypeStatusService;
    private final WmsInReceiptTaskMaterialMapper wmsInReceiptTaskMaterialMapper;
    private final IWmsInReceiptTaskMaterialService iWmsInReceiptTaskMaterialService;
    private final IWmsInReceiptService inReceiptService;
    private final IBasicMaterialService materialService;
    private final DockTaskRecordMapMapper taskRecordMapMapper;
    private final IBasicCustomerService iBasicCustomerService;
    private final ISysBaseAPI iSysBaseAPI;
    private final IWmsBasicWarehouseAreaService warehouseAreaService;
    private final IBasicMaterialService iBasicMaterialService;
    private final MesDockingRepeaterService mesDockingRepeaterService;
    private final WmsOutReceiptTaskMaterialMapper wmsOutReceiptTaskMaterialMapper;
    private final IWmsOutReceiptTaskMaterialService iWmsOutReceiptTaskMaterialService;
    private final WmsRepertoryMapper wmsRepertoryMapper;
    private final WmsBasicWarehouseMapper warehouseMapper;
    private final WmsBasicMaterialStockInfoMapper materialStockInfoMapper;
    private final WmsMoveReceiptMapper wmsMoveReceiptMapper;
    private final IBasicCustomerService basicCustomerService;
    private final IMesSiteService mesSiteService;

    private final WmsWarehousePaperConfigMapper paperConfigMapper;
    @Value("${material.code.dp:}")
    private String dpCode;
    @Value("${material.code.dpfc:}")
    private String dpfcCode;
    @Value("${material.code.zhjtzt:}")
    private String zhjtztCode;
    @Value("${material.code.bzxjl:}")
    private String bzxjlCode;
    @Value(value = "${wms.config.personnel.mes:}")
    private String personnelMes;
    @Value("${material.code.khtl:}")
    private String khtlCode;
    @Value("${material.code.hjjlb:}")
    private String hjjlbCode;
    @Value("${material.code.hjrk:}")
    private String hjrkCode;
    @Value("${material.code.zjtgt:}")
    private String zjtgtCode;
    @Value("${material.code.scrk:}")
    private String scrkCode;

    @Value("${wms.config.warehouse.code001:}")
    private String code001;
    @Value("${wms.config.warehouse.code002:}")
    private String code002;
    @Value("${wms.config.warehouse.code003:}")
    private String code003;
    @Value("${wms.config.warehouse.code004:}")
    private String code004;
    @Value("${wms.config.warehouse.code005:}")
    private String code005;
    @Value("${wms.config.warehouse.code006:}")
    private String code006;

    @Override
    public MesBaseResponseVO scoringStorage(ScoringStorageOrScratchRequestVO scoringStorageRequestVO) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";

        log.info("WMS实时接收到的数据是:{} ", scoringStorageRequestVO);
        DockDataReceiveRecord record = getRecord(scoringStorageRequestVO);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        String basicMaterial = getBasicMaterial(khtlCode);
        if (StrUtil.isEmpty(basicMaterial)) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData("未根据物料编码查询到物料id");
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            return MesBaseResponseVO.failure("未根据物料编码查询到物料id");
        }

        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
        material.setInputBatchCode(StrUtil.join(",", scoringStorageRequestVO.getInPutBatch()));
        material.setIsMergeRoll(scoringStorageRequestVO.getCombine());
        material.setBatchCode(scoringStorageRequestVO.getOutPutBatch());
        material.setLength(scoringStorageRequestVO.getLength());
        material.setWidth(scoringStorageRequestVO.getWidth());
        material.setThickness(scoringStorageRequestVO.getThickness());
        material.setWmsBasicMaterialId(basicMaterial);
        material.setExpectedWarehousingTime(new Date());
        material.setExtraText(JSON.toJSONString(scoringStorageRequestVO));
        material.setMotherBatchCode(scoringStorageRequestVO.getParentBatch());
        material.setIsMergeRoll(scoringStorageRequestVO.getCombine());
        material.setPlanProductSite(scoringStorageRequestVO.getSite());
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(khtlCode, material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
        // 重量为库存数量
        material.setPlanQuantity(scoringStorageRequestVO.getWeight());
        material.setSteelCoilNumber(scoringStorageRequestVO.getOutPutBatch());
        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(scoringStorageRequestVO.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);
        list.add(material);
        try {
            wmsInReceiptTask(list, recordId, CODE, DocumentTask.R03, scoringStorageRequestVO, "");
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("刻痕入库请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    /**
     * 根据物料编码查询信息
     *
     * @param materialCode
     * @param vo
     * @return void
     * @author hansen
     * @since 2023/12/26 13:24
     */
    private <T> Object materialAssignment(String materialCode, T vo) {
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        List<BasicMaterial> basicMaterials = materialService.list(new LambdaQueryWrapper<BasicMaterial>()
                .eq(BasicMaterial::getCode, materialCode)
                .eq(BasicMaterial::getDelFlag, "0"));
        BasicMaterial materialY = new BasicMaterial();
        if (CollectionUtil.isNotEmpty(basicMaterials)) {
            materialY = basicMaterials.get(0);
        }
        // 入库单处理逻辑
        if (vo instanceof WmsInReceiptTaskMaterial) {
            WmsInReceiptTaskMaterial inReceiptTaskMaterial = JSON.parseObject(JSON.toJSONString(vo), WmsInReceiptTaskMaterial.class);
            if (ObjectUtil.isNotNull(materialY)) {
                inReceiptTaskMaterial.setWmsBasicUnitId(materialY.getInventoryUnitId());
                if (StrUtil.isNotBlank(materialY.getAssistantUnitId())) {
                    inReceiptTaskMaterial.setAssistQuantity(BigDecimal.ONE);
                    inReceiptTaskMaterial.setUnitAssistId(materialY.getAssistantUnitId());
                    return inReceiptTaskMaterial;
                }
                return inReceiptTaskMaterial;
            }
        }
        // 出库单处理逻辑
        else if (vo instanceof WmsOutReceiptTaskMaterial) {
            WmsOutReceiptTaskMaterial outReceiptTaskMaterial = JSON.parseObject(JSON.toJSONString(vo), WmsOutReceiptTaskMaterial.class);
            if (ObjectUtil.isNotNull(materialY)) {
                outReceiptTaskMaterial.setWmsBasicUnitId(materialY.getInventoryUnitId());
                if (StrUtil.isNotBlank(materialY.getAssistantUnitId())) {
                    outReceiptTaskMaterial.setAssistQuantity(BigDecimal.ONE);
                    outReceiptTaskMaterial.setUnitAssistId(materialY.getAssistantUnitId());
                    return outReceiptTaskMaterial;
                }
                return outReceiptTaskMaterial;
            }
        }
        // 移库单处理逻辑
        else if (vo instanceof WmsMoveReceiptMaterial) {
            WmsMoveReceiptMaterial moveReceiptTaskMaterial = JSON.parseObject(JSON.toJSONString(vo), WmsMoveReceiptMaterial.class);
            if (ObjectUtil.isNotNull(materialY)) {
                moveReceiptTaskMaterial.setWmsBasicUnitId(materialY.getInventoryUnitId());
                if (StrUtil.isNotBlank(materialY.getAssistantUnitId())) {
                    moveReceiptTaskMaterial.setAssistQuantity(BigDecimal.ONE);
                    moveReceiptTaskMaterial.setUnitAssistId(materialY.getAssistantUnitId());
                    return moveReceiptTaskMaterial;
                }
                return moveReceiptTaskMaterial;
            }
        }
        return vo;
    }

//    /**
//     * 获取入库推荐库位
//     *
//     * @param documentType
//     * @param id
//     * @return
//     */
//    private WarehousingStrategyOneVO getRecommendWarehouse(String documentType, String id, String warehouseId) {
//        //初始化一个入库策略对象
//        WarehousingStrategyOneParamVO oneParamVO = new WarehousingStrategyOneParamVO();
//        oneParamVO.setDocumentType(documentType);
//        oneParamVO.setMaterialId(id);
//        oneParamVO.setWarehouseId(warehouseId);
//        // 获取推荐库位
//        return inReceiptService.warehousingStrategyOne(oneParamVO);
//    }

    @Override
    public MesBaseResponseVO longitudinalShearStorage(LongitudinalShearStorageRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        // 初始化入库任务物料
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        // 赋值
        for (LongitudinalShearStorageRequestVO.Detail detail : vo.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            // 库存数量为重量
            material.setPlanQuantity(BigDecimal.valueOf(detail.getWeight()));
            material.setExtraText(JSON.toJSONString(vo));
            material.setExpectedWarehousingTime(new Date());
            material.setBatchCode(detail.getBatchId());
            material.setWidth(detail.getWidth());
            material.setOutsideDiameter(BigDecimal.valueOf(detail.getDiameter()));
            material.setGrossWeight(BigDecimal.valueOf(detail.getWeight()));
            material.setPlanProductSite(detail.getPlanSite());
            material.setOriginalSystemNumber(vo.getOrderCode());
            String basicMaterial = getBasicMaterial(bzxjlCode);
            if (StrUtil.isEmpty(basicMaterial)) {
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultData("未根据物料编码查询到物料id");
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                return MesBaseResponseVO.failure("未根据物料编码查询到物料id");
            }
            material.setWmsBasicMaterialId(basicMaterial);
            material.setPlanProductOrderNumber(detail.getPlanOrderCode());
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setSequence(detail.getSequence());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, recordId, CODE, DocumentTask.R12, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵剪入库请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO verticalCuttingIsCalledPaperTube(VerticalCuttingIsCalledPaperTubeRequestVO vo) {
        final String CODE = "8aaa81a48afd63d0018afd7552140034";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        // 校验推送的物料数据是否重复
        List<VerticalCuttingIsCalledPaperTubeRequestVO.Detail> detail = vo.getDetail();
        if (detail.size() >= 2) {
            VerticalCuttingIsCalledPaperTubeRequestVO.Detail detailNO1 = detail.get(0);
            for (int i = 0; i < detail.size() - 1; i++) {
                VerticalCuttingIsCalledPaperTubeRequestVO.Detail detailNext = detail.get(i + 1);
                if (detailNO1.getMaterialCode().equals(detailNext.getMaterialCode())
                        && detailNO1.getSpec().equals(detailNext.getSpec())) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("不可推送重复的物料数据!!!");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                }
            }
        }
        List<WmsMoveReceiptMaterial> list = new ArrayList<>(16);

        List<DictModel> siteDicts = iSysBaseAPI.getDictItems("cross_cut_material_site");
        for (VerticalCuttingIsCalledPaperTubeRequestVO.Detail d : detail) {
            WmsMoveReceiptMaterial material = new WmsMoveReceiptMaterial();
//            material.setRemark(vo.getRemark());
            material.setExtraText(JSON.toJSONString(vo));
            material.setOriginalSystemNumber(vo.getOrderCode());
            if (StrUtil.isNotEmpty(d.getMaterialCode())) {
                // 获取物料ID
                String id = getBasicMaterial(d.getMaterialCode());
                if (StrUtil.isEmpty(id)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(id);
                }
            }
            // 如果物料启用了辅单位就赋值
            Object o = materialAssignment(d.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsMoveReceiptMaterial.class);
            // 从即时库存获取移出库区
            List<WmsRepertory> repertoryList = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getWmsBasicWarehouseId, queryWarehouseCode(code003))
                    .eq(WmsRepertory::getMaterialId, material.getWmsBasicMaterialId()));
            Set<String> areaIds = repertoryList.stream().map(WmsRepertory::getWmsBasicWarehouseAreaId).collect(Collectors.toSet());
            Map<String, WmsBasicWarehouseArea> areaMap = warehouseAreaService.listByIds(areaIds).stream().collect(Collectors.toMap(WmsBasicWarehouseArea::getId, Function.identity()));
            repertoryList = repertoryList.stream().filter(a -> ObjectUtil.equal(areaMap.get(a.getWmsBasicWarehouseAreaId()).getAreaType(), "4")).collect(Collectors.toList());  // 类型等于普通库区
            if (CollectionUtil.isEmpty(repertoryList)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("即时库存的四期纸筒仓中没有该物料的库存数据");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            repertoryList = repertoryList.stream().filter(a -> a.getStockQuantity().compareTo(BigDecimal.valueOf(d.getNumber())) != -1).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(repertoryList)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("即时库存的四期纸筒仓中该物料的库存数量小于需要移库的数量");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            if (StringUtils.isBlank(vo.getSite())) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("站点不能为空");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setTransferFromAreaId(repertoryList.get(0).getWmsBasicWarehouseAreaId());
            material.setTransferFromLocationId(repertoryList.get(0).getWmsBasicWarehouseAreaLocationId());
            material.setRepertoryId(repertoryList.get(0).getId());
            // 根据生产站点获取移入库区
//            List<DictModel> dicts = siteDicts.stream().filter(a -> vo.getSite().equals(a.getText())).collect(Collectors.toList());
//            if (CollectionUtil.isEmpty(dicts)) {
//                MesBaseResponseVO failure = MesBaseResponseVO.failure("没有对应的站点");
//                record.setStatus(DockDataStatus.FAILURE);
//                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
//                record.setResultData(failure.toString());
//                return failure;
//            }
//            List<WmsBasicWarehouseArea> areas = warehouseAreaService.list(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
//                    .eq(WmsBasicWarehouseArea::getWmsBasicWarehouseId, queryWarehouseCode(code003)));

//            List<WmsBasicWarehouseArea> areaList = areas.stream()
//                    .filter(a -> StrUtil.contains(a.getProductSite(), dicts.get(0).getValue())).collect(Collectors.toList());
            WmsWarehousePaperConfig config = getPaperConfig(vo.getSite(), MOVE_Y14);
            if (config == null || StrUtil.isBlank(config.getWarehouseAreaId())) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("没有匹配该站点的库区");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setTransferToAreaId(config.getWarehouseAreaId());
            material.setTransferQuantity(BigDecimal.valueOf(d.getNumber()));
            list.add(material);
        }

        try {
            this.wmsMoveReceipt(list, recordId, CODE, MOVE_Y14, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("WMS发送纵剪叫纸筒异常:", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    private WmsWarehousePaperConfig getPaperConfig(String site, String businessCode) {
        WmsWarehousePaperConfig config = paperConfigMapper.selectOne(new LambdaQueryWrapper<WmsWarehousePaperConfig>()
                .eq(WmsWarehousePaperConfig::getSite, site)
                .eq(WmsWarehousePaperConfig::getBusinessCode, businessCode));
        return config;
    }

    @Override
    public MesBaseResponseVO verticalAndHorizontalCutting(VerticalAndHorizontalCuttingRequestVO vo) {
        final String CODE = "8aaa816f8b173ce8018b173e384a0008";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();

        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        for (VerticalAndHorizontalCuttingRequestVO.Detail detail : vo.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            // 根据产线编码查询仓库编码
            WmsWarehousePaperConfig paperConfig = getPaperConfig(vo.getSite(), DocumentTask.R09);
            if (paperConfig == null || StrUtil.isBlank(paperConfig.getWarehouseId())) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseAreaId(paperConfig.getWarehouseAreaId());
            material.setWmsBasicWarehouseId(paperConfig.getWarehouseId());
            material.setBatchCode(detail.getBatchId());
            material.setPlanProductSite(vo.getSite());
            if (ObjectUtil.isNotEmpty(detail.getNumber())) {
                material.setPlanQuantity(new BigDecimal(detail.getNumber()));
            }
            material.setExpectedWarehousingTime(new Date());
            material.setExtraText(JSON.toJSONString(vo));
//            material.setProductNumber(vo.getOrderCode());
            material.setOriginalSystemNumber(vo.getOrderCode());
            if (StrUtil.isNotEmpty(detail.getMaterialCode())) {
                // 获取物料ID
                String id = getBasicMaterial(detail.getMaterialCode());
                if (StrUtil.isEmpty(id)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(id);
                }
                // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
                Object o = materialAssignment(detail.getMaterialCode(), material);
                material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            }
            list.add(material);
        }

        try {
            wmsInReceiptTask(list, recordId, CODE, DocumentTask.R09, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵横剪退纸筒请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO laminatedAuxiliaryMaterialOrdering(LaminatedAuxiliaryMaterialOrderingRequestVO vo) {
        final String CODE = "8aaa81de8b02fccf018b0305675e000f";

        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>();
        WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
        material.setAskMaterialArea(vo.getAskRange());
        // 获取物料ID
        String id = getBasicMaterial(dpfcCode);
        if (StrUtil.isEmpty(id)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(id);
        }
        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(vo.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);
        material.setPlanQuantity(vo.getTableQuantity());
        material.setExpectedOutboundTime(new Date());
        material.setExtraText(JSON.toJSONString(vo));
        material.setOriginalSystemNumber(vo.getOrderCode());
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(dpfcCode, material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
        list.add(material);

        try {
            wmsOutReceiptTask(list, record.getId(), CODE, OutboundTask.C22, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("叠片辅材叫料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO laminatedAuxiliaryMaterialReturn(LaminatedAuxiliaryMaterialReturnRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();

        // 获取物料ID
        String id = getBasicMaterial(dpfcCode);
        if (StrUtil.isEmpty(id)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(id);
        }

//        material.setRemark(vo.getRemark());
        material.setPlanQuantity(vo.getTableQuantity());
        material.setAskMaterialArea(vo.getAskRange());
        material.setExpectedWarehousingTime(new Date());
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(dpfcCode, material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
        material.setExtraText(JSON.toJSONString(vo));
        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(vo.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);
//        material.setProductNumber(vo.getOrderCode());
        material.setOriginalSystemNumber(vo.getOrderCode());
        list.add(material);

        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R23, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("叠片辅材退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO packagingLineMaterialOrdering(PackagingLineMaterialOrderingRequestVO vo) {
        if (MesInterfaceTypeEnum.BZ_TAKE_AUTO.getCode().equals(vo.getTaskType())) {
            final String CODE = "8aaa81de8b02fccf018b0305675e000f";
            log.info("WMS实时接收到的数据是:{} ", vo);
            DockDataReceiveRecord record = getRecord(vo);
            HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
            httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
            List<WmsOutReceiptTaskMaterial> list = new ArrayList<>();
            for (PackagingLineMaterialOrderingRequestVO.Detail detail : vo.getDetail()) {
                WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
                material.setBatchCode(detail.getBatchId());
                material.setWidth(detail.getWidth());
                if (ObjectUtil.isNotEmpty(detail.getDiameter())) {
                    material.setOutsideDiameter(new BigDecimal(detail.getDiameter()));
                }
                material.setRollArm(detail.getArm());
                // 获取物料ID
                String basicMaterial = getBasicMaterial(bzxjlCode);
                if (StrUtil.isEmpty(basicMaterial)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(basicMaterial);
                }
                // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
                Object o = materialAssignment(bzxjlCode, material);
                material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
                material.setBatchCode(detail.getBatchId());
                // 根据产线编码查询仓库编码
                String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(vo.getSite());
                if (StrUtil.isEmpty(warehouseIdBySite)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                }
                material.setWmsBasicWarehouseId(warehouseIdBySite);
                // 库存单位为重量
                material.setPlanQuantity(BigDecimal.valueOf(detail.getWeight()));
                material.setExpectedOutboundTime(new Date());
                material.setExtraText(JSON.toJSONString(vo));
                list.add(material);
            }
            try {
                wmsOutReceiptTask(list, record.getId(), CODE, OutboundTask.C45, vo, vo.getOrderCode());
                record.setStatus(DockDataStatus.SUCCESS);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
                record.setResultData(record.toString());
            } catch (Exception e) {
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultData(e.toString());
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                log.error("包装线叫料请求异常信息: ", e);
                return MesBaseResponseVO.failure(e.getMessage());
            }
            return MesBaseResponseVO.ok();
        } else {
            final String CODE = "8aaa81de8b02fccf018b0305675e000f";
            log.info("WMS实时接收到的数据是:{} ", vo);
            DockDataReceiveRecord record = getRecord(vo);
            try {
                String className = this.getClass().getName();
                String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
                record.setInterfaceName(className + ":" + methodName);
            } catch (Exception e) {

            }
            List<WmsOutReceiptTaskMaterial> list = new ArrayList<>();
            for (PackagingLineMaterialOrderingRequestVO.Detail detail : vo.getDetail()) {
                WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
                material.setBatchCode(detail.getBatchId());
                material.setWidth(detail.getWidth());
                material.setAssistQuantity(BigDecimal.ONE);
                if (ObjectUtil.isNotNull(detail.getDiameter())) {
                    material.setOutsideDiameter(new BigDecimal(detail.getDiameter()));
                }
                material.setRollArm(detail.getArm());
                // 获取物料ID
                String basicMaterial = getBasicMaterial(bzxjlCode);
                if (StrUtil.isEmpty(basicMaterial)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(basicMaterial);
                }
                // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
                Object o = materialAssignment(bzxjlCode, material);
                material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
                material.setBatchCode(detail.getBatchId());
                // 根据产线编码查询仓库编码
                String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(vo.getSite());
                if (StrUtil.isEmpty(warehouseIdBySite)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                }
                material.setWmsBasicWarehouseId(warehouseIdBySite);
                // 库存单位为重量
                material.setPlanQuantity(BigDecimal.valueOf(detail.getWeight()));
                material.setExpectedOutboundTime(new Date());
                material.setExtraText(JSON.toJSONString(vo));
                list.add(material);
            }
            try {
                wmsOutReceiptTask(list, record.getId(), CODE, OutboundTask.C15, vo, vo.getOrderCode());
                record.setStatus(DockDataStatus.SUCCESS);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
                record.setResultData(record.toString());
            } catch (Exception e) {
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultData(e.toString());
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                log.error("包装线叫料请求异常信息: ", e);
                return MesBaseResponseVO.failure(e.getMessage());
            }
            return MesBaseResponseVO.ok();
        }
    }

    @Override
    public MesBaseResponseVO packagingLineReturn(PackagingLineReturnRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        for (PackagingLineReturnRequestVO.Detail detail : vo.getDetail()) {
            //未使用 detail-> weight
            // vo-> orderCode
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            material.setBatchCode(detail.getBatchId());
            material.setWidth(detail.getWidth());
            material.setAssistQuantity(BigDecimal.ONE);
            if (ObjectUtil.isNotNull(detail.getDiameter())) {
                material.setOutsideDiameter(new BigDecimal(detail.getDiameter()));
            }
            material.setRollArm(detail.getArm());
//            material.setRemark(vo.getRemark());
            material.setWmsBasicMaterialId("1");
            material.setPlanQuantity(new BigDecimal(1));
            material.setExpectedWarehousingTime(new Date());
            material.setExtraText(JSON.toJSONString(vo));
//            material.setProductNumber(vo.getOrderCode());
            material.setOriginalSystemNumber(vo.getOrderCode());
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R16, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("包装线退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO finishedProductWarehousing(FinishedProductWarehousingScaleRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("包装入库(定尺)WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        for (FinishedProductWarehousingScaleRequestVO.Detail detail : vo.getDetail()) {
            //未使用 detail-> netWeight
            // vo-> orderCode ironType
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            material.setBatchCode(detail.getBatchId());
            material.setWidth(detail.getWidth());
            if (ObjectUtil.isNotNull(detail.getDiameter())) {
                material.setOutsideDiameter(new BigDecimal(detail.getDiameter()));
            }
            if (ObjectUtil.isNotNull(detail.getGrossWeight())) {
                material.setGrossWeight(new BigDecimal(detail.getGrossWeight()));
            }
//            material.setRemark(vo.getRemark());
            material.setCreateBy("admin");
            material.setMeasuredWeight(BigDecimal.valueOf(detail.getNetWeight()));
            material.setPlanProductSite(vo.getSite());
            // 获取物料ID
            String basicMaterial = getBasicMaterial(detail.getMaterialCode());
            if (StrUtil.isEmpty(basicMaterial)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(basicMaterial);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setPlanQuantity(BigDecimal.valueOf(detail.getNetWeight()));
            material.setExpectedWarehousingTime(new Date());
            material.setExtraText(JSON.toJSONString(vo));
//            material.setProductNumber(vo.getOrderCode());
            material.setOriginalSystemNumber(vo.getOrderCode());
            material.setCustomerCode(detail.getCustomCode());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R26, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("成品入库请求（定尺）异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO finishedProductWarehousingIron(FinishedProductWarehousingIronRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        for (FinishedProductWarehousingIronRequestVO.Detail detail : vo.getDetail()) {
            //未使用 detail-> netWeight
            // vo-> orderCode ironType
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            material.setBatchCode(detail.getBatchId());
            if (ObjectUtil.isNotNull(detail.getGrossWeight())) {
                material.setGrossWeight(new BigDecimal(detail.getGrossWeight()));
            }
            if (ObjectUtil.isNotNull(detail.getNetWeight())) {
                material.setMeasuredWeight(new BigDecimal(detail.getNetWeight()));
            }
            // 获取物料ID
            String basicMaterial = getBasicMaterial(detail.getMaterialCode());
            if (StrUtil.isEmpty(basicMaterial)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(basicMaterial);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setPlanQuantity(detail.getNumber());
            material.setExpectedWarehousingTime(new Date());
            material.setExtraText(JSON.toJSONString(vo));
//            material.setProductNumber(vo.getOrderCode());
            material.setOriginalSystemNumber(vo.getOrderCode());
            material.setPlanProductSite(vo.getSite());
            material.setCustomerCode(detail.getCustomCode());

            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }

        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R25, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("成品入库请求（铁心）异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO syncExamIronResult(FinishedProductWarehousingIronRequestVO vo) {
        log.info("WMS实时接收到的数据是:{} ", vo);
        List<FinishedProductWarehousingIronRequestVO.Detail> detail = vo.getDetail();
        // 根据批次号查询任务物料明细，更新质检结果【检验结果=合格，检验状态=已检验】
        List<String> batchIds = detail.stream().map(t -> t.getBatchId()).collect(Collectors.toList());

        List<WmsInReceiptTaskMaterial> list = iWmsInReceiptTaskMaterialService.list(
                new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                        .in(WmsInReceiptTaskMaterial::getBatchCode, batchIds));
        if (CollectionUtil.isEmpty(list)) {
            return MesBaseResponseVO.failure("同步【铁心】质检结果,存在查询不到当前批次号【" +
                    batchIds.stream().collect(Collectors.joining(",")) + "】的任务明细");
        }
        list = list.stream().filter(t -> !InspectStatusEnum.INSPECTED.getName().equals(t.getInspectStatus()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(t -> {
                t.setInspectStatus(InspectStatusEnum.INSPECTED.getName());
                t.setInspectResult(InspectResultEnum.PASS.getName());
                t.setInspectTime(new Date());
                // 抽检1 全检2
                t.setInspectionMethod("2");
            });
            iWmsInReceiptTaskMaterialService.updateBatchById(list);
        } else {
            return MesBaseResponseVO.failure("同步【铁心】质检结果,当前批次号【" +
                    batchIds.stream().collect(Collectors.joining(",")) + "】无需更新");
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO scoringScratch(ScoringReturnOrScratchRequestVO vo) {
        final String CODE = "8aaa81de8b02fccf018b0305675e000f";

        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>();
        WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
        // 获取物料ID
        String basicMaterial = getBasicMaterial(khtlCode);
        if (StrUtil.isEmpty(basicMaterial)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(basicMaterial);
        }
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(khtlCode, material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
        material.setBatchCode(vo.getBatchId());
        // 获取库存数量
        List<WmsRepertory> repertories = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                .eq(WmsRepertory::getBatchCode, vo.getBatchId()));
        if (CollectionUtil.isNotEmpty(repertories)) {
            WmsRepertory repertory = repertories.get(0);
            material.setPlanQuantity(repertory.getUsableQuantity());
        }
        material.setExpectedOutboundTime(new Date());
        material.setExtraText(JSON.toJSONString(vo));

        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(vo.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);

        list.add(material);

        try {
            wmsOutReceiptTask(list, record.getId(), CODE, OutboundTask.C04, vo, "");
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("刻痕叫料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO scoringReturn(ScoringReturnOrScratchRequestVO vo) {
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";

        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        //未使用 vo-> detail
        WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
        material.setBatchCode(vo.getBatchId());
        // 获取物料ID
        String basicMaterial = getBasicMaterial(khtlCode);
        if (StrUtil.isEmpty(basicMaterial)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(basicMaterial);
        }
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(khtlCode, material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
        // 重量为库存数量
        material.setPlanQuantity(vo.getWeight());
        material.setWmsBasicMaterialId(basicMaterial);
        material.setExpectedWarehousingTime(new Date());
        material.setExtraText(JSON.toJSONString(vo));
        material.setPlanProductSite(vo.getSite());

        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(vo.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);

        list.add(material);
        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R05, vo, "");
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("刻痕退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO crossShearCallMaterial(CrossShearCallMaterialRequestVO vo) {
        log.info("横剪叫料请求-WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>(16);
        for (CrossShearCallMaterialRequestVO.Detail dto : vo.getDetail()) {
            WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
            material.setWidth(dto.getWidth());
            material.setBatchCode(dto.getBatchId());
            material.setOutsideDiameter(BigDecimal.valueOf(dto.getDiameter()));
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(bzxjlCode, material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
            if (StrUtil.isNotEmpty(dto.getMaterialCode())) {
                // 获取物料ID
                String id = getBasicMaterial(bzxjlCode);
                if (StrUtil.isEmpty(id)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(id);
                }
            }
            // 横剪叫料重量为即使库存中的重量
            List<WmsRepertory> repertoryList = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getBatchCode, dto.getBatchId()));
            if (CollectionUtil.isNotEmpty(repertoryList)) {
                WmsRepertory repertory = repertoryList.get(0);
                // 库存单位为重量
                material.setPlanQuantity(repertory.getUsableQuantity());
            }
            material.setBatchCode(dto.getBatchId());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            // 根据批次号查询即时库存
//            if (StringUtils.isNotBlank(dto.getBatchId())) {
//                List<WmsRepertory> wmsRepertories = wmsRepertoryMapper.selectList(new LambdaQueryWrapper<WmsRepertory>().eq(WmsRepertory::getBatchCode, dto.getBatchId()));
//                if (CollectionUtil.isNotEmpty(wmsRepertories)) {
//                    WmsRepertory wmsRepertory = wmsRepertories.get(0);
//                    material.setPlanQuantity(wmsRepertory.getStockQuantity());
//                    material.setWmsBasicUnitId(wmsRepertory.getWmsBasicUnitId());
//                }
//            }

            material.setExpectedOutboundTime(new Date());
            material.setExtraText(JSON.toJSONString(vo));
            material.setPlanProductSite(vo.getSite());
            material.setProductNumber(vo.getOrderCode());
            material.setRollArm(dto.getArm());
            list.add(material);
        }
        WmsOutReceiptTaskPage wmsOutReceiptTaskPage = new WmsOutReceiptTaskPage();
        wmsOutReceiptTaskPage.setDocumentCode(FillRuleUtil.executeRule(DirectionOfInventoryEnum.OUTBOUND.getCode(), JSON.parseObject(DirectionOfInventoryEnum.OUTBOUND.getRemark())).toString());
        wmsOutReceiptTaskPage.setWmsOutReceiptTaskMaterialList(list);
        wmsOutReceiptTaskPage.setTaskDate(DateUtil.parseDate(DateUtil.now()));
        wmsOutReceiptTaskPage.setOwnerType("1");
        wmsOutReceiptTaskPage.setOrganization("A04A01");
        wmsOutReceiptTaskPage.setSysOrgCode("A04A01");
        wmsOutReceiptTaskPage.setOwner("A05");
        wmsOutReceiptTaskPage.setOriginalSystem(SystemConstants.MES);
        wmsOutReceiptTaskPage.setRequestPerson("MES请求人员");
        wmsOutReceiptTaskPage.setCreateBy(personnelMes);
        wmsOutReceiptTaskPage.setRequestTime(DateUtil.now());

        wmsOutReceiptTaskPage.setTaskDate(new Date());
        wmsOutReceiptTaskPage.setTaskType(vo.getTaskType());
        wmsOutReceiptTaskPage.setSiteCode(vo.getSite());
        wmsOutReceiptTaskPage.setProductLine(vo.getLineName());
        wmsOutReceiptTaskPage.setTaskCode(vo.getTaskCode());
        wmsOutReceiptTaskPage.setProductOrderNumber(vo.getOrderCode());

        //创建流程
        BaseFlowDto base = new BaseFlowDto();
        // 根据单据类型创建不同的单据
        if (vo.getTaskType().equals(MesInterfaceTypeEnum.HJ_TAKE.getCode())) {
            wmsOutReceiptTaskPage.setDocumentType(ReceiptsEnum.C13.getCode());
            base.setDocumentType(ReceiptsEnum.C13.getCode());
            base.setCode(ReceiptsEnum.C13.getRemark());
            base.setBusinessType(ReceiptsEnum.C13.getType());
        } else if (vo.getTaskType().equals(MesInterfaceTypeEnum.HJ_TAKE_MANUAL.getCode())) {
            wmsOutReceiptTaskPage.setDocumentType(ReceiptsEnum.C43.getCode());
            base.setDocumentType(ReceiptsEnum.C43.getCode());
            base.setCode(ReceiptsEnum.C43.getRemark());
            base.setBusinessType(ReceiptsEnum.C43.getType());
        }

        // 600线设置横剪叫料手动
        if ("ADZ-04".equals(vo.getSite())) {
            wmsOutReceiptTaskPage.setDocumentType(ReceiptsEnum.C43.getCode());
            base.setDocumentType(ReceiptsEnum.C43.getCode());
            base.setCode(ReceiptsEnum.C43.getRemark());
            base.setBusinessType(ReceiptsEnum.C43.getType());
        }

        base.setData(wmsOutReceiptTaskPage);
        try {
            workFlowService.commit(base);
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.getMessage());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("横剪叫料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        String taskId = base.getInfoId();
        DockTaskRecordMap map = new DockTaskRecordMap();
        map.setTaskId(taskId);
        map.setRecordId(recordId);
        map.setMesTaskCode(vo.getTaskCode());
        map.setSite(vo.getSite());
        dockTaskRecordMapMapper.insert(map);
        return MesBaseResponseVO.ok();
    }

    /**
     * 通过部门code获取部门全部信息
     *
     * @param user
     * @return org.jeecg.common.system.vo.SysDepartModel
     * @author hansen
     * @since 2023/10/6 10:31
     */
    @Override
    public SysDepartModel getSysDepartModel(LoginUser user) {
        // 通过部门code查询部门id
        String departIdsByOrgCode = systemApiController.getDepartIdsByOrgCode(user.getOrgCode());
        // 通过部门id获取部门的全部信息
        return systemApiController.selectAllById(departIdsByOrgCode);
    }

    @Override
    public MesBaseResponseVO crossShearingMaterialWithdrawal(CrossShearingMaterialWithdrawalRequestVO vo) {
        final String DOCUMENT_TYPE = "R14";
        final String CODE = "8aaa81c08afed23d018afed275910003";

        log.info("横剪退料-WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        for (CrossShearingMaterialWithdrawalRequestVO.Detail detail : vo.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            // 获取物料ID
            String basicMaterial = getBasicMaterial(bzxjlCode);
            if (StrUtil.isEmpty(basicMaterial)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(basicMaterial);
            }
            material.setBatchCode(detail.getBatchId());
            material.setGrossWeight(BigDecimal.valueOf(detail.getWeight()));
            material.setWidth(detail.getWidth());
            material.setOutsideDiameter(BigDecimal.valueOf(detail.getDiameter()));
            material.setWmsBasicMaterialId(basicMaterial);
            // 库存数量为重量
            material.setPlanQuantity(BigDecimal.valueOf(detail.getWeight()));
            material.setExpectedWarehousingTime(new Date());
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(bzxjlCode, material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setRollArm(detail.getArm());
            material.setOriginalSystemNumber(vo.getOrderCode());
            material.setExtraText(JSON.toJSONString(vo));
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            material.setPlanProductSite(vo.getSite());
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("横剪退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO transverseShearCallMaterialPlate(TransverseShearCallMaterialPlateRequestVO vo) {
        final String DOCUMENT_TYPE = "C17";
        final String CODE = "8aaa81de8b02fccf018b0305675e000f";
        log.info("横剪叫料板--WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>(16);
        WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
        // 获取物料ID
        String basicMaterial = getBasicMaterial(vo.getMaterialCode());
        if (StrUtil.isEmpty(basicMaterial)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(basicMaterial);
        }
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(vo.getMaterialCode(), material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(vo.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);
        material.setPlanQuantity(BigDecimal.valueOf(vo.getUpNumber() + vo.getDownNumber()));
        material.setExpectedOutboundTime(new Date());
        material.setExtraText(JSON.toJSONString(vo));
        list.add(material);

        try {
            wmsOutReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, vo, "");
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("横剪叫料板请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO transverseShearCalledScrapBox(TransverseShearCalledScrapBoxRequestVO vo) {
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        if (StringUtils.isBlank(record.getBusinessCode())) {
            record.setBusinessCode("C38");
        }
        //同步给MDS
        MDSTheTransverseShearIsCalledAScrapBinRequestVO requestVO = new MDSTheTransverseShearIsCalledAScrapBinRequestVO();
        requestVO.setTaskCode(vo.getTaskCode());
        requestVO.setOperateTime(DateUtil.parse(DateUtil.format(vo.getOperateTime(), DatePattern.NORM_DATETIME_PATTERN)));
        requestVO.setTaskType(vo.getTaskType());
        requestVO.setOperatorName(vo.getOperatorName());
        requestVO.setLineName(vo.getLineName());
        requestVO.setSite(vo.getSite());
        //文档上该值固定
        requestVO.setTakeLocation("F-01");
//        requestVO.setRemark(vo.getRemark());
        requestVO.setDetail(vo.getDetail());
        requestVO.setTaskStatus(MdsStatusEnum.TASK_STARTED.getCode());
        MdsBaseResponseVO mdsBaseResponseVO = null;
        DockDataSendRecord dockDataSendRecord = new DockDataSendRecord();
        try {
            mdsBaseResponseVO = mdsDockingRepeaterService.mdsTheTransverseShearIsCalledAScrapBin(requestVO);
            log.error("请求MDS响应 :{}", mdsBaseResponseVO.toString());
        } catch (Exception e) {
            log.error("请求MDS叫废料箱失败", e);
            dockDataSendRecord.setStatus(DockDataStatus.FAILURE);
        } finally {
            dockDataSendRecord.setUuid(IdUtil.fastSimpleUUID());
            dockDataSendRecord.setSource(SystemConstants.WMS);
            dockDataSendRecord.setTarget(SystemConstants.MDS);
            if (ObjectUtil.isNotNull(mdsBaseResponseVO)) {
                dockDataSendRecord.setData(mdsBaseResponseVO.toString());
            } else {
                dockDataSendRecord.setData("横剪叫废料箱请求MDS响应为空");
            }
            dockDataSendRecord.setSendTime(new Date());
            if (StringUtils.isBlank(dockDataSendRecord.getBusinessCode())) {
                dockDataSendRecord.setBusinessCode("C38");
            }
            dockDataSendRecordMapper.insert(dockDataSendRecord);
        }
        MesBaseResponseVO baseResponseVO = new MesBaseResponseVO<>();
        if (ObjectUtil.isNotNull(mdsBaseResponseVO)) {
            //通知MES状态结果
            if ("success".equals(mdsBaseResponseVO.getTarget())) {
                MesBaseRequestVO baseRequestVO = BeanUtil.toBean(vo, MesBaseRequestVO.class);
                baseRequestVO.setTaskStatus("TASK_STARTED");
                baseRequestVO.setOperateTime(new Date());
                baseRequestVO.setOperatorName("WMS系统");
                baseResponseVO = mesDockingRepeaterService.updateStatus(baseRequestVO);
            }
        }
        return baseResponseVO;
    }

    @Override
    public MesBaseResponseVO crossCutTheScrapBin(CrossCutTheScrapBinRequestVO vo) {
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        if (StringUtils.isBlank(record.getBusinessCode())) {
            record.setBusinessCode("R39");
        }
        //同步给MDS
        MDSCrossCutTheScrapBinRequestVO requestVO = new MDSCrossCutTheScrapBinRequestVO();
        requestVO.setTaskCode(vo.getTaskCode());
        requestVO.setOperateTime(DateUtil.parse(DateUtil.format(vo.getOperateTime(), DatePattern.NORM_DATETIME_PATTERN)));
        requestVO.setTaskType(vo.getTaskType());
        requestVO.setOperatorName(vo.getOperatorName());
        requestVO.setLineName(vo.getLineName());
        requestVO.setSite(vo.getSite());
        //文档上该值固定
        requestVO.setReturnLocation("F-01");
        requestVO.setRemark(vo.getRemark());
        requestVO.setDetail(vo.getDetail());
        requestVO.setTaskStatus(MdsStatusEnum.TASK_STARTED.getCode());
        MdsBaseResponseVO mdsBaseResponseVO = null;
        DockDataSendRecord dockDataSendRecord = new DockDataSendRecord();
        try {
            mdsBaseResponseVO = mdsDockingRepeaterService.mdsCrossCutTheScrapBin(requestVO);
            log.error("请求MDS响应 :{}", mdsBaseResponseVO.toString());
        } catch (Exception e) {
            log.error("请求MDS退废料箱失败", e);
            dockDataSendRecord.setStatus(DockDataStatus.FAILURE);
        } finally {
            dockDataSendRecord.setUuid(IdUtil.fastSimpleUUID());
            dockDataSendRecord.setSource(SystemConstants.WMS);
            dockDataSendRecord.setTarget(SystemConstants.MDS);
            if (ObjectUtil.isNotNull(mdsBaseResponseVO)) {
                dockDataSendRecord.setData(mdsBaseResponseVO.toString());
            } else {
                dockDataSendRecord.setData("横剪退废料箱请求MDS响应为空");
            }
            dockDataSendRecord.setSendTime(new Date());
            if (StringUtils.isBlank(dockDataSendRecord.getBusinessCode())) {
                dockDataSendRecord.setBusinessCode("R39");
            }
            dockDataSendRecordMapper.insert(dockDataSendRecord);
        }
        MesBaseResponseVO baseResponseVO = new MesBaseResponseVO<>();
        if (ObjectUtil.isNotNull(mdsBaseResponseVO)) {
            //通知MES状态结果
            if ("success".equals(mdsBaseResponseVO.getTarget())) {
                MesBaseRequestVO baseRequestVO = BeanUtil.toBean(vo, MesBaseRequestVO.class);
                baseRequestVO.setTaskStatus("TASK_STARTED");
                baseRequestVO.setOperateTime(new Date());
                baseRequestVO.setOperatorName("WMS系统");
                baseResponseVO = mesDockingRepeaterService.updateStatus(baseRequestVO);
            }
        }
        return baseResponseVO;
    }

    @Override
    public MesBaseResponseVO scissorEntry(ScissorEntryRequestVO vo) {
        final String DOCUMENT_TYPE = "R19";
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";

        log.info("横剪入库--WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        for (ScissorEntryRequestVO.Detail detail : vo.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            // 计划数量为重量
            material.setPlanQuantity(BigDecimal.valueOf(detail.getWeight()));
            material.setExtraText(JSON.toJSONString(vo));
            material.setPillar(detail.getModelName());
            material.setMaterialDirection(String.valueOf(detail.getDirection()));
            material.setStationNum(detail.getTableCode());
            material.setBatchCode(detail.getBatchId());
            // 获取物料ID
            String basicMaterial = getBasicMaterial(hjrkCode);
            if (StrUtil.isEmpty(basicMaterial)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(basicMaterial);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(hjrkCode, material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setExpectedWarehousingTime(new Date());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
//            material.setProductNumber(vo.getOrderCode());
            material.setOriginalSystemNumber(vo.getOrderCode());
            // 位置
            material.setLocation(detail.getPosition());
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("横剪入库请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO laminationCall(LaminationCallRequestVO param) {
        log.info("叠片叫料--WMS实时接收到的数据是:{} ", param);

        final String DOCUMENT_TYPE = "C20";
        final String CODE = "8aaa81de8b02fccf018b0305675e000f";

        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();

        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>(16);
        WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
        material.setPlanQuantity(BigDecimal.valueOf(param.getTableQuantity()));
        material.setExtraText(JSON.toJSONString(param));
        // 获取物料ID
        String basicMaterial = getBasicMaterial(dpCode);
        if (StrUtil.isEmpty(basicMaterial)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(basicMaterial);
        }
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(dpCode, material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(param.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);
        material.setOriginalSystemNumber(param.getOrderCode());
        list.add(material);

        try {
            wmsOutReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("叠片叫料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO laminationReturn(LaminationReturnRequestVO param) {
        final String DOCUMENT_TYPE = "R21";
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";

        log.info("叠片退料--WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();

        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);

        for (LaminationReturnRequestVO.Detail detail : param.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
//            material.setRemark(param.getRemark());
            material.setPlanQuantity(BigDecimal.valueOf(param.getTableQuantity()));
            material.setExtraText(JSON.toJSONString(param));
            material.setPillar(detail.getModelName());
            material.setMaterialDirection(String.valueOf(detail.getDirection()));
            material.setStationNum(detail.getTableCode());
            material.setBatchCode(detail.getBatchId());
            material.setLocation(detail.getPosition());
            material.setStationNum(detail.getTableCode());
            // 获取物料ID
            String basicMaterial = getBasicMaterial(dpCode);
            if (StrUtil.isEmpty(basicMaterial)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(basicMaterial);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(dpCode, material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setExpectedWarehousingTime(new Date());
            material.setPlanProductSite(param.getSite());
            material.setOriginalSystemNumber(param.getOrderCode());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(param.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }

        try {
            wmsInReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("叠片退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        MDSLaminationAndRefeedingRequestVO mdsvo =
                BeanUtil.toBean(param, MDSLaminationAndRefeedingRequestVO.class);
        mdsvo.setTaskStatus(MdsStatusEnum.TASK_RECEIVED.getCode());
        MdsBaseResponseVO mdsBaseResponseVO = mdsDockingRepeaterService.mdsLaminationAndRefeeding(mdsvo);
        return mdsBaseResponseVO.toMesResponseVO();
    }

    /**
     * 根据物料编码获取物料ID
     *
     * @param code
     * @return java.lang.String
     * @author hansen
     * @since 2023/10/26 13:29
     */
    private String getBasicMaterial(String code) throws JeecgBootException {
        List<BasicMaterial> list = materialService.list(new LambdaQueryWrapper<BasicMaterial>().eq(BasicMaterial::getCode, code));
        if (CollectionUtil.isNotEmpty(list)) {
            BasicMaterial basicMaterial = list.get(0);
            return basicMaterial.getId();
        }
        return "";
    }

    @Override
    public MesBaseResponseVO laminationCallMaterialCompletionReturn(LaminationCallMaterialCompletionReturnColumnMaterialDetails param) {
        log.info("WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO laminatedRefeedingPlate(LaminatedRefeedingPlateRequestVO param) {
        log.info("叠片退料板--WMS实时接收到的数据是:{} ", param);

        final String DOCUMENT_TYPE = "R18";
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";

        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
//        material.setRemark(param.getRemark());
        material.setPlanQuantity(BigDecimal.valueOf(param.getQuantity()));
        material.setExtraText(JSON.toJSONString(param));
        material.setOriginalSystemNumber(param.getOrderCode());
        // 根据产线编码查询仓库编码
        String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(param.getSite());
        if (StrUtil.isEmpty(warehouseIdBySite)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        material.setWmsBasicWarehouseId(warehouseIdBySite);
        // 获取物料ID
        String basicMaterial = getBasicMaterial(param.getMaterialCode());
        if (StrUtil.isEmpty(basicMaterial)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        } else {
            material.setWmsBasicMaterialId(basicMaterial);
        }
        // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
        Object o = materialAssignment(param.getMaterialCode(), material);
        material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
        material.setExpectedWarehousingTime(new Date());
        list.add(material);
        try {
            wmsInReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("横剪退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO slittingIsCalledMaterial(SlittingIsCalledMaterialRequestVO param) {
        log.info("WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();

        final String DOCUMENT_TYPE = "C06";
        final String CODE = "8aaa81de8b02fccf018b0305675e000f";

        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>(16);
        List<SlittingIsCalledMaterialRequestVO.Detail> collect = param.getDetail().stream().filter(t -> ObjectUtil.isNotNull(t)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)) {
            MesBaseResponseVO failure = MesBaseResponseVO.failure("传过来的物料信息为空");
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(failure.toString());
            return failure;
        }
        for (SlittingIsCalledMaterialRequestVO.Detail detail : param.getDetail()) {
            WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
//            material.setRemark(param.getRemark());
            material.setExtraText(JSON.toJSONString(param));
            material.setBatchCode(detail.getBatchId());
            material.setWidth(detail.getWidth());
            material.setOutsideDiameter(BigDecimal.valueOf(detail.getDiameter()));
            if (ObjectUtil.isNotNull(detail.getWeight())) {
                material.setGrossWeight(new BigDecimal(detail.getWeight()));
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
            material.setExpectedOutboundTime(new Date());
            material.setOriginalSystemNumber(param.getOrderCode());
            if (StrUtil.isNotEmpty(detail.getMaterialCode())) {
                // 获取物料ID
                String id = getBasicMaterial(detail.getMaterialCode());
                if (StrUtil.isEmpty(id)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(id);
                }
            } else {
                String s = queryMaterialCodeByBatchCode(detail.getBatchId());
                if (StrUtil.isEmpty(s)) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过批次号查询到物料");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                } else {
                    material.setWmsBasicMaterialId(s);
                }
            }
            // 纵剪叫料重量为即使库存中的重量
            List<WmsRepertory> repertoryList = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getBatchCode, detail.getBatchId()));
            if (CollectionUtil.isNotEmpty(repertoryList)) {
                WmsRepertory repertory = repertoryList.get(0);
                // 库存单位为重量
                material.setPlanQuantity(repertory.getUsableQuantity());
            }
            material.setBatchCode(detail.getBatchId());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(param.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }
        try {
            wmsOutReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵剪叫料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO theMaterialIsWithdrawnByLongitudinalShearing(TheMaterialIsWithdrawnByLongitudinalShearingRequestVO param) {
        log.info("WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        String recordId = record.getId();

        final String DOCUMENT_TYPE = "R07";
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";

        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        for (TheMaterialIsWithdrawnByLongitudinalShearingRequestVO.Detail detail : param.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
//            material.setRemark(param.getRemark());
            material.setPlanQuantity(BigDecimal.valueOf(detail.getWeight()));
            material.setExtraText(JSON.toJSONString(param));
            material.setBatchCode(detail.getBatchId());
            material.setWidth(detail.getWidth());
            material.setOutsideDiameter(BigDecimal.valueOf(detail.getDiameter()));
            material.setGrossWeight(BigDecimal.valueOf(detail.getWeight()));
            // 获取物料ID
            String id = getBasicMaterial(detail.getMaterialCode());
            if (StrUtil.isEmpty(id)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(id);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setOriginalSystemNumber(param.getOrderCode());
            material.setPlanProductSite(param.getSite());
            material.setExpectedWarehousingTime(new Date());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(param.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, recordId, CODE, DOCUMENT_TYPE, param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵剪退料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO returnSteelBarrel(ReturnSteelBarrelRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        for (ReturnSteelBarrelRequestVO.Detail detail : vo.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesBackHouseByOutboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            // 获取物料ID
            String id = getBasicMaterial(detail.getSpec());
            if (StrUtil.isEmpty(id)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(id);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getSpec(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            if (ObjectUtil.isNotNull(detail.getNumber())) {
                material.setPlanQuantity(new BigDecimal(detail.getNumber()));
            }
            material.setExpectedWarehousingTime(new Date());
            material.setExtraText(JSON.toJSONString(vo));
//            material.setProductNumber(vo.getOrderCode());
            material.setOriginalSystemNumber(vo.getOrderCode());
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R31, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵剪退钢筒请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MesBaseResponseVO updateStatus(MesBaseRequestVO vo) {
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        record.setNodeName("");
        String message = "";
        log.info("mes-》wms:同步任务状态请求开始：【{}】", vo);
        try {
            if (MesStatusEnum.FORCE_FINISHED.getCode().equals(vo.getTaskStatus())) {
                // 判断任务类型区分强制完成发送给mds还是ems
                if(MesInterfaceTypeEnum.ZJ_TAKE_PAPER.getCode().equals(vo.getTaskType()) ||
                        MesInterfaceTypeEnum.ZJ_RETURN_PAPER.getCode().equals(vo.getTaskType())){
                    // 发送ems强制关闭
                    BaseRequestDTO request = new BaseRequestDTO();
                    BeanUtil.copyProperties(vo, request);
                    EmsBaseResponseVO emsBaseResponseVO = emsDockingRepeaterService.forceFinish(request);
                    if ("success".equals(emsBaseResponseVO.getTarget())) {
                        // 强制关闭流程节点
                        closeFlow(vo);
                    } else {
                        log.error("mes-》wms:同步任务状态请求异常：【同步强制关闭给mds请求异常】");
                        message = "同步强制关闭给ems请求异常: " + emsBaseResponseVO.toString();
                    }
                }else{
                    // 发送mds强制关闭
                    ForceCompleteRequestVO completeRequestVO = new ForceCompleteRequestVO();
                    BeanUtil.copyProperties(vo, completeRequestVO);
                    MdsBaseResponseVO mdsBaseResponseVO = mdsDockingRepeaterService.forceComplete(completeRequestVO);
                    if (MdsBaseResponseVO.SUCCESS.equals(mdsBaseResponseVO.getTarget())) {
                        // 强制关闭流程节点
                        closeFlow(vo);
                    } else {
                        log.error("mes-》wms:同步任务状态请求异常：【同步强制关闭给mds请求异常】");
                        message = "同步强制关闭给mds请求异常: " + mdsBaseResponseVO.toString();
                    }
                }
            }
            // 纵剪入库接收任务结束推送流程
            else if (MesInterfaceTypeEnum.ZJ_STOCK.getCode().equals(vo.getTaskType())) {
                if (MesStatusEnum.SEND_MATERIAL_FINISHED.getCode().equals(vo.getTaskStatus())) {
                    final String CODE = "8aaa849e8c0f2815018c0f28155c0000";
                    record.setNodeName("同步MES结束状态");
                    try {
                        commit(vo, CODE);
                        record.setStatus(DockDataStatus.SUCCESS);
                        record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
                        record.setResultData(record.toString());
                    } catch (Exception e) {
                        record.setStatus(DockDataStatus.FAILURE);
                        record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                        record.setResultData(e.toString());
                        message = e.getMessage();
                    }
                }
            } else {
                String taskType = vo.getTaskType();
                if (MesInterfaceTypeEnum.ZJ_RETURN_REPLY.getCode().equals(taskType)) {
                    //纵剪退料更新wms状态-待卸料状态扭转
                    final String CODE = "8aaa80cb8b894705018b8947051e0000";
                    record.setNodeName("卸载");
                    commit(vo, CODE);
                    log.info("开始" + MesInterfaceTypeEnum.ZJ_RETURN_REPLY.getRemark() + "状态扭转");
                } else if (MesInterfaceTypeEnum.ZJ_STOCK_REPLY.getCode().equals(taskType)) {
                    final String CODE = "8aaa80008bd6b2e5018bd6b37e610001";
                    record.setNodeName("信息接收");
                    //纵剪入库更新任务信息
                    String taskCode = vo.getTaskCode();
                    DockTaskRecordMap map = dockTaskRecordMapMapper.selectOne(new LambdaQueryWrapper<DockTaskRecordMap>()
                            .eq(DockTaskRecordMap::getMesTaskCode, taskCode));
                    List<WmsInReceiptTaskMaterial> wmsInReceiptTaskMaterials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                            .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, map.getTaskId()));
                    String replace = vo.getData().toString().replace("[", "").replace("]", "").replaceAll("=", ":");
                    JSONObject entries = JSONUtil.parseObj(replace);
                    String carNo = entries.get("carNo").toString();
                    String armNo = entries.get("armNo").toString();
                    wmsInReceiptTaskMaterials.forEach(o -> {
                        o.setVehicleNumber(carNo);
                        o.setArmNo(armNo);
                    });
                    iWmsInReceiptTaskMaterialService.updateBatchById(wmsInReceiptTaskMaterials);
                    commit(vo, CODE);
                }
                // 通过任务更新接口，更新wms任务毛重字段信息
                else if (MesInterfaceTypeEnum.CP_STOCK_DC.getCode().equals(taskType)) {
                    // 获取传输的信息
                    String jsonObject = JSON.parseObject(JSON.toJSONString(vo)).getString("data");
                    UpdateGrossWeightOfFinishedProductsRequestVO updateVo = JSON.parseObject(jsonObject, UpdateGrossWeightOfFinishedProductsRequestVO.class);
                    // 查询物料编码
                    String basicMaterial = getBasicMaterial(updateVo.getMaterialCode());
                    // 根据任务编号查询物料信息
                    DockTaskRecordMap byTaskCode = taskRecordMapMapper.getByTaskCode(vo.getTaskCode());
                    List<WmsInReceiptTaskMaterial> wmsInReceiptTaskMaterials = wmsInReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                            .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, byTaskCode.getTaskId()));
                    // 当该任务下有多个物料信息时筛选出匹配的物料信息
                    WmsInReceiptTaskMaterial wmsInReceiptTaskMaterial = wmsInReceiptTaskMaterials.stream().filter(in ->
                            in.getBatchCode().equals(updateVo.getBatchId())
                                    && in.getWmsBasicMaterialId().equals(basicMaterial)
                    ).findFirst().orElse(null);
                    // 更新成品入库定尺物料信息
                    if (wmsInReceiptTaskMaterial != null) {
                        wmsInReceiptTaskMaterialMapper.update(null, new LambdaUpdateWrapper<WmsInReceiptTaskMaterial>()
                                .eq(WmsInReceiptTaskMaterial::getId, wmsInReceiptTaskMaterial.getId())
                                .set(WmsInReceiptTaskMaterial::getGrossWeight, updateVo.getGrossWeight()));
                    }
                } else if (MesInterfaceTypeEnum.BZ_TAKE_XC.getCode().equals(taskType)) {
                    final String CODE = "8aaa847c8c1ec0ac018c1ec1b76e0001";
                    record.setNodeName("信息接收");
                    //包装叫料更新小车信息
                    String taskCode = vo.getTaskCode();
                    DockTaskRecordMap map = dockTaskRecordMapMapper.selectOne(new LambdaQueryWrapper<DockTaskRecordMap>()
                            .eq(DockTaskRecordMap::getMesTaskCode, taskCode));
                    List<WmsOutReceiptTask> wmsOutReceiptTask = outReceiptTaskService.list(new LambdaQueryWrapper<WmsOutReceiptTask>()
                            .eq(WmsOutReceiptTask::getTaskCode, taskCode));
                    List<WmsOutReceiptTaskMaterial> wmsOutReceiptTaskMaterials = wmsOutReceiptTaskMaterialMapper.selectList(new LambdaQueryWrapper<WmsOutReceiptTaskMaterial>()
                            .eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId, map.getTaskId()));
                    String replace = vo.getData().toString().replace("[", "").replace("]", "").replaceAll("=", ":");
                    JSONObject entries = JSONUtil.parseObj(replace);
                    String carNo = entries.get("carNo").toString();
                    String armNo = entries.get("armNo").toString();
                    wmsOutReceiptTaskMaterials.forEach(o -> {
                        o.setVehicleNumber(carNo);
                        o.setArmNo(armNo);
                    });
                    iWmsOutReceiptTaskMaterialService.updateBatchById(wmsOutReceiptTaskMaterials);
                    commit(vo, CODE);
                    log.info("------------------");
                } else if (MesInterfaceTypeEnum.BZ_TAKE.getCode().equals(taskType)) {
                    if (MesStatusEnum.SEND_MATERIAL_FINISHED.getCode().equals(vo.getTaskStatus())) {
                        final String CODE = "8aaa847c8c1ec0ac018c1ec42e640002";
                        record.setNodeName("同步MES结束状态");
                        try {
                            commit(vo, CODE);
                            record.setStatus(DockDataStatus.SUCCESS);
                            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
                            record.setResultData(record.toString());
                        } catch (Exception e) {
                            record.setStatus(DockDataStatus.FAILURE);
                            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                            record.setResultData(e.toString());
                            message = e.getMessage();
                        }
                    }
                }
            }
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            log.error("mes-》wms:同步任务状态请求失败：【{}】", e.getMessage(), e);
            message = e.toString();
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            record.setResultData(e.toString());
        }
        if (StringUtils.isNotBlank(message)) {
            return MesBaseResponseVO.failure(message);
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO updateScoringStorage(UpdateScoringStorageRequestVO vo) {
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        try {
            String taskCode = vo.getTaskCode();
            // 根据taskCode查询物料信息
            DockTaskRecordMap map = dockTaskRecordMapMapper.selectOne(new LambdaQueryWrapper<DockTaskRecordMap>()
                    .eq(DockTaskRecordMap::getMesTaskCode, taskCode));
            WmsInReceiptTaskMaterial wmsInReceiptTaskMaterials = wmsInReceiptTaskMaterialMapper.selectOne(new LambdaQueryWrapper<WmsInReceiptTaskMaterial>()
                    .eq(WmsInReceiptTaskMaterial::getWmsInReceiptTaskId, map.getTaskId()));
            // 查询物料编码
            String basicMaterial = getBasicMaterial(vo.getMaterialCode());
            // 更新属性
            wmsInReceiptTaskMaterials.setSteelCoilNumber(vo.getBatchId());
            wmsInReceiptTaskMaterials.setWmsBasicMaterialId(basicMaterial);
            wmsInReceiptTaskMaterials.setBatchCode(vo.getSapBatch());
            wmsInReceiptTaskMaterials.setReceiptCertificate(vo.getMblnr());
            iWmsInReceiptTaskMaterialService.updateById(wmsInReceiptTaskMaterials);
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
            //更新流程信息
            BaseFlowDto baseFlowDto = new BaseFlowDto();
            baseFlowDto.setInfoId(map.getTaskId());
            baseFlowDto.setCode("8aaa85df8ca38f68018ca39b9bc40006");
            workFlowService.commit(baseFlowDto);
        } catch (Exception e) {
            log.error("mes-》wms:刻痕入库更新信息请求失败：【{}】", e.getMessage(), e);
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            return MesBaseResponseVO.failure(e.toString());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO theSlittingIsCalledATray(TheSlittingIsCalledATrayRequestVO param) {
        log.info("纵剪叫托盘-WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>(16);
        for (TheSlittingIsCalledATrayRequestVO.Detail detail : param.getDetail()) {
            WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
            // 获取物料ID
            String id = getBasicMaterial(detail.getSpec());
            if (StrUtil.isEmpty(id)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(id);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getSpec(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
            material.setPlanQuantity(new BigDecimal(detail.getNumber()));
//            material.setProductNumber(vo.getOrderCode());
            material.setExtraText(JSON.toJSONString(param));
            material.setExpectedOutboundTime(new Date());
            material.setOriginalSystemNumber(param.getOrderCode());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesOutHouseByOutboundSite(param.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            list.add(material);
        }
        try {
            wmsOutReceiptTask(list, record.getId(), "8aaa81de8b02fccf018b0305675e000f", "C40", param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵剪叫托盘请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }


    @Override
    public MesBaseResponseVO zjConsumePaper(ZJUsePaperRequestVO param) {
        //纵剪消耗纸筒
        log.info("纵剪消耗纸筒-WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        // 校验推送的物料数据是否重复
        List<ZJUsePaperRequestVO.Detail> detail = param.getDetail();
        if (detail.size() >= 2) {
            ZJUsePaperRequestVO.Detail detailNO1 = detail.get(0);
            for (int i = 0; i < detail.size() - 1; i++) {
                ZJUsePaperRequestVO.Detail detailNext = detail.get(i + 1);
                if (detailNO1.getMaterialCode().equals(detailNext.getMaterialCode())
                        && detailNO1.getSpec().equals(detailNext.getSpec())) {
                    MesBaseResponseVO failure = MesBaseResponseVO.failure("不可推送重复的物料数据!!");
                    record.setStatus(DockDataStatus.FAILURE);
                    record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                    record.setResultData(failure.toString());
                    return failure;
                }
            }
        }
        List<WmsOutReceiptTaskMaterial> list = new ArrayList<>(16);
        String c44 = "C44";
        for (ZJUsePaperRequestVO.Detail vo : detail) {
            WmsOutReceiptTaskMaterial material = new WmsOutReceiptTaskMaterial();
            material.setPlanQuantity(BigDecimal.valueOf(vo.getNumber()));
            material.setExtraText(JSON.toJSONString(param));
            material.setExpectedOutboundTime(new Date());
            material.setSpecificationModel(vo.getSpec());
            // 获取物料ID
            String id = getBasicMaterial(vo.getMaterialCode());
            if (StrUtil.isEmpty(id)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(id);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(vo.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsOutReceiptTaskMaterial.class);
            materialAssignment(vo.getMaterialCode(), material);
            // 根据产线编码查询仓库编码
            WmsWarehousePaperConfig config = getPaperConfig(param.getSite(), c44);
            if (config == null || StrUtil.isBlank(config.getWarehouseAreaId())) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseAreaId(config.getWarehouseAreaId());
            material.setWmsBasicWarehouseId(config.getWarehouseId());
            material.setOriginalSystemNumber(param.getOrderCode());
            list.add(material);
        }
        try {
            wmsOutReceiptTask(list, record.getId(), "8aaa81de8b02fccf018b0305675e000f", c44, param, param.getOrderCode());


            try {
                List<WmsMoveReceiptMaterial> movelist = new ArrayList<>();
                List<WmsBasicWarehouseArea> areas = warehouseAreaService.list(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                        .eq(WmsBasicWarehouseArea::getWmsBasicWarehouseId, queryWarehouseCode(code003)));
//                List<DictModel> siteDicts = iSysBaseAPI.getDictItems("cross_cut_material_site");
//                List<DictModel> dicts = siteDicts.stream().filter(a -> param.getSite().equals(a.getText())).collect(Collectors.toList());
//                if (CollectionUtil.isEmpty(dicts)) {
//                    throw new JeecgBootException(param.getSite() + "没有对应的站点");
//                }
                //查普通车间
                List<WmsBasicWarehouseArea> areaList = areas.stream()
                        .filter(a -> "4".equals(a.getAreaType())).collect(Collectors.toList());
                if (CollectionUtil.isEmpty(areaList)) {
                    throw new JeecgBootException("仓库：" + code003 + " 没有匹配到普通车间");
                }
                WmsWarehousePaperConfig config = getPaperConfig(param.getSite(), c44);
                List<WmsMoveReceipt> moveReceipts = wmsMoveReceiptMapper.getMoveReceipt(MOVE_Y14, config.getWarehouseAreaId());
                if (CollectionUtil.isNotEmpty(moveReceipts)) {
                    log.error("已存在对应的移库单，{}", moveReceipts);
                    throw new JeecgBootException("已存在对应的移库单");
                }

//                Set<String> collect = areas.stream().filter(a -> !"5".equals(a.getAreaType()))
//                        .map(WmsBasicWarehouseArea::getId).collect(Collectors.toSet());

                for (WmsOutReceiptTaskMaterial taskMaterial : list) {
                    List<WmsBasicMaterialStockInfo> materialStockInfos = materialStockInfoMapper.selectList(new LambdaQueryWrapper<WmsBasicMaterialStockInfo>()
                            .eq(WmsBasicMaterialStockInfo::getWmsBasicMaterialId, taskMaterial.getWmsBasicMaterialId())
                            .eq(WmsBasicMaterialStockInfo::getWarehouseAreaId, taskMaterial.getWmsBasicWarehouseAreaId()));
                    if (CollectionUtil.isEmpty(materialStockInfos)) {
                        log.error("物料id：{}，库区id：{} 未找到对应物料库区信息", taskMaterial.getWmsBasicMaterialId(),
                                taskMaterial.getWmsBasicWarehouseAreaId());
                        continue;
                    }
//                    Set<String> materialAreas = materialStockInfos.stream().map(WmsBasicMaterialStockInfo::getWarehouseAreaId).collect(Collectors.toSet());
//                    HashSet<String> resSet = new HashSet<>();
//                    resSet.addAll(collect);
//                    resSet.retainAll(materialAreas);
//                    if (CollectionUtil.isEmpty(resSet)) {
//                        log.error("物料id：{}，未配置对应的纸筒仓库区", taskMaterial.getWmsBasicWarehouseId());
//                        continue;
//                    }

                    WmsRepertory wmsRepertory = wmsRepertoryMapper.selectOne(new LambdaQueryWrapper<WmsRepertory>()
                            .eq(WmsRepertory::getMaterialId, taskMaterial.getWmsBasicMaterialId())
                            .eq(WmsRepertory::getWmsBasicWarehouseAreaId, taskMaterial.getWmsBasicWarehouseAreaId()));
                    if (wmsRepertory == null) {
                        log.error("物料id：{}，库区id：{} 未找到对应的即时库存信息", taskMaterial.getWmsBasicMaterialId(),
                                taskMaterial.getWmsBasicWarehouseAreaId());
                        continue;
                    }

//                    WmsBasicWarehouse warehouse = warehouseMapper.selectById(taskMaterial.getWmsBasicWarehouseId());
//                    if (warehouse == null || !"4".equals(warehouse.getAttribute())) {
//                        log.error("仓库id:{} 不是车间仓,详情：{}", taskMaterial.getWmsBasicWarehouseId(), warehouse);
//                        continue;
//                    }
                    WmsBasicMaterialStockInfo materialStockInfo = materialStockInfos.stream().filter(ms -> ms.getWarehouseAreaId().equals(areaList.get(0).getId())).findFirst().get();

                    WmsMoveReceiptMaterial moveReceiptMaterial = new WmsMoveReceiptMaterial();
                    if (wmsRepertory.getStockQuantity().compareTo(materialStockInfo.getSafeInventory()) != 1) {
                        moveReceiptMaterial.setWmsBasicMaterialId(taskMaterial.getWmsBasicMaterialId());
                        moveReceiptMaterial.setTransferQuantity(materialStockInfo.getMaxInventory().subtract(materialStockInfo.getSafeInventory()));
                        moveReceiptMaterial.setTransferToAreaId(config.getWarehouseAreaId());
                        moveReceiptMaterial.setTransferFromAreaId(areaList.get(0).getId());
                        movelist.add(moveReceiptMaterial);
                    }
                }
                if (CollectionUtil.isNotEmpty(movelist)) {

                    WmsMoveReceiptPage moveReceiptPage = new WmsMoveReceiptPage();
                    moveReceiptPage.setDocumentCode(FillRuleUtil.executeRule(MOVE_DOCUMENT_CODE, JSON.parseObject(MOVE_PARAM)).toString());
                    moveReceiptPage.setDocumentType(MOVE_Y14);
                    moveReceiptPage.setWmsMoveReceiptMaterialList(movelist);
                    moveReceiptPage.setBusinessDate(new Date());
                    moveReceiptPage.setHasChild(1);
                    moveReceiptPage.setCreateBy(personnelMes);
                    moveReceiptPage.setOwnerType("1");
                    moveReceiptPage.setSysOrgCode("A04A01");
                    moveReceiptPage.setOrganization("A04A01");
                    moveReceiptPage.setTransferFromOwner("A05");
                    moveReceiptPage.setTransferFromDepartment("A04A01");
                    moveReceiptPage.setTransferFromWarehouseId(queryWarehouseCode(code003));  // 默认四期纸筒仓
                    moveReceiptPage.setOriginalSystem(SystemConstants.MES);
                    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                    moveReceiptPage.setWarehouseKeeper(sysUser.getRealname());
                    final String CODE = "8aaa81a48afd63d0018afd7552140034";
                    //创建流程
                    BaseFlowDto base = new BaseFlowDto();
                    base.setDocumentType(MOVE_Y14);
                    base.setCode(CODE);
                    base.setData(moveReceiptPage);
                    base.setBusinessType(BusinessTypeEnum.move_type.toString());
                    workFlowService.commit(base);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            //
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("纵剪消耗纸筒请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO scStockSuper(SCStockSuperRequestVO param) {
        //MES发起生产入库(超大卷)入库的时候，先包装叫料的出库任务（自动完成，批次号取投产批次号），再产生入库任务。
        log.info("生产入库（超大卷）-WMS实时接收到的数据是:{} ", param);
        DockDataReceiveRecord record = getRecord(param);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>(16);
        List<WmsOutReceiptTaskMaterial> outList = new ArrayList<>();
        for (SCStockSuperRequestVO.Detail detail : param.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
//            material.setRemark(param.getRemark());
            material.setPlanQuantity(detail.getNumber());
            material.setExtraText(JSON.toJSONString(param));
            material.setBatchCode(detail.getBatchId());
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(detail.getMaterialCode(), material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            material.setGrossWeight(BigDecimal.valueOf(detail.getGrossWeight()));
            material.setMeasuredWeight(BigDecimal.valueOf(detail.getNetWeight()));
            // 获取物料ID
            String id = getBasicMaterial(detail.getMaterialCode());
            if (StrUtil.isEmpty(id)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(id);
            }

            material.setExpectedWarehousingTime(new Date());
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(param.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
//            material.setProductNumber(param.getOrderCode());
            material.setOriginalSystemNumber(param.getOrderCode());

            material.setCustomerCode(detail.getCustomCode());
            list.add(material);
            //////////////////////////////////////////////////////////////////////////////
            //包装叫料
            WmsOutReceiptTaskMaterial outMaterial = new WmsOutReceiptTaskMaterial();
            outMaterial.setPlanQuantity(detail.getQuantity());
            outMaterial.setExtraText(JSON.toJSONString(param));
            outMaterial.setBatchCode(detail.getInPutBatch());
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object oaa = materialAssignment(detail.getMaterialCode(), outMaterial);
            outMaterial = JSON.parseObject(JSON.toJSONString(oaa), WmsOutReceiptTaskMaterial.class);
            if (ObjectUtil.isNotNull(detail.getGrossWeight())) {
                outMaterial.setGrossWeight(BigDecimal.valueOf(detail.getGrossWeight()));
            }
            if (ObjectUtil.isNotNull(detail.getNetWeight())) {
                outMaterial.setMeasuredWeight(BigDecimal.valueOf(detail.getNetWeight()));
            }
            outMaterial.setWmsBasicMaterialId(getBasicMaterial(detail.getParentBatch()));
            outMaterial.setExpectedOutboundTime(new Date());
            WmsRepertory repertory = repertoryService.getOne(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getBatchCode, detail.getInPutBatch())
                    .eq(WmsRepertory::getMaterialId, getBasicMaterial(detail.getParentBatch()))
                    .last("limit 1")
            );
            if (repertory != null) {
                outMaterial.setWmsBasicWarehouseId(repertory.getWmsBasicWarehouseId());
                outMaterial.setWmsBasicWarehouseAreaId(repertory.getWmsBasicWarehouseAreaId());
                outMaterial.setWmsBasicWarehouseAreaLocationId(repertory.getWmsBasicWarehouseAreaLocationId());
            }
            outMaterial.setOriginalSystemNumber(param.getOrderCode());
            outList.add(outMaterial);
        }
        try {
            wmsOutReceiptTask(outList, record.getId(), "8aaa81de8b02fccf018b0305675e000f", "C34", param, param.getOrderCode());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
        } catch (Exception e) {
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("生成包装叫料请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        try {
            wmsInReceiptTask(list, record.getId(), "8aaa81dc8b02e1b0018b02ee2f5f001c", "R35", param, param.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("生产入库（超大卷）请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    @Override
    public MesBaseResponseVO stripMaterialIsTransferredOutOfStorage(StripMaterialIsTransferredOutOfStorageRequestVO vo) {
        final String CODE = "8aaa81dc8b02e1b0018b02ee2f5f001c";
        log.info("WMS实时接收到的数据是:{} ", vo);
        DockDataReceiveRecord record = getRecord(vo);
        HttpServletRequest httpServletRequest = SpringContextUtils.getHttpServletRequest();
        httpServletRequest.setAttribute(SystemConstants.AttachKey.RECEIVE, record);
        List<WmsInReceiptTaskMaterial> list = new ArrayList<>();
        for (StripMaterialIsTransferredOutOfStorageRequestVO.Detail detail : vo.getDetail()) {
            WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
            // 根据产线编码查询仓库编码
            String warehouseIdBySite = mesSiteService.getMesInHouseByInboundSite(vo.getSite());
            if (StrUtil.isEmpty(warehouseIdBySite)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过站点查询到仓库");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            }
            material.setWmsBasicWarehouseId(warehouseIdBySite);
            // 获取物料ID
            String id = getBasicMaterial(bzxjlCode);
            if (StrUtil.isEmpty(id)) {
                MesBaseResponseVO failure = MesBaseResponseVO.failure("未通过物料code查询到物料");
                record.setStatus(DockDataStatus.FAILURE);
                record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
                record.setResultData(failure.toString());
                return failure;
            } else {
                material.setWmsBasicMaterialId(id);
            }
            // 如果物料启用了辅单位管理, 就对辅单位数量进行赋值
            Object o = materialAssignment(bzxjlCode, material);
            material = JSON.parseObject(JSON.toJSONString(o), WmsInReceiptTaskMaterial.class);
            // 计划数量为重量
            material.setPlanQuantity(new BigDecimal(detail.getWeight()));
            material.setWidth(BigDecimal.valueOf(detail.getWidth()));
            material.setOutsideDiameter(BigDecimal.valueOf(detail.getDiameter()));
            material.setExpectedWarehousingTime(new Date());
            material.setBatchCode(detail.getBatchId());
            material.setGrossWeight(BigDecimal.valueOf(detail.getWeight()));
            material.setExtraText(JSON.toJSONString(vo));
            material.setOriginalSystemNumber(vo.getOrderCode());
            list.add(material);
        }
        try {
            wmsInReceiptTask(list, record.getId(), CODE, DocumentTask.R60, vo, vo.getOrderCode());
            record.setStatus(DockDataStatus.SUCCESS);
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_0);
            record.setResultData(record.toString());
        } catch (Exception e) {
            record.setStatus(DockDataStatus.FAILURE);
            record.setResultData(e.toString());
            record.setResultCode(CommonConstant.ANNOUNCEMENT_SEND_STATUS_1);
            log.error("条料调拨出库提醒请求异常信息: ", e);
            return MesBaseResponseVO.failure(e.getMessage());
        }
        return MesBaseResponseVO.ok();
    }

    private DockDataReceiveRecord getRecord(Object data) {
        MesBaseRequestVO bean = BeanUtil.toBean(data, MesBaseRequestVO.class);
        DockDataReceiveRecord dockDataReceiveRecord = new DockDataReceiveRecord();
        dockDataReceiveRecord.setBusinessCode(bean.getTaskType());
        return dockDataReceiveRecord;
    }

    private <T extends MesBaseRequestVO> void wmsInReceiptTask(List<WmsInReceiptTaskMaterial> list,
                                                               String recordId,
                                                               String code,
                                                               String documentType,
                                                               T vo,
                                                               String orderCode) {
        WmsInReceiptTaskPage wmsInReceiptTaskPage = new WmsInReceiptTaskPage();
        wmsInReceiptTaskPage.setDocumentCode(FillRuleUtil.executeRule(WAREHOUSE_DOCUMENT_CODE, JSON.parseObject(WAREHOUSE_PARAM)).toString());
        wmsInReceiptTaskPage.setDocumentType(documentType);
        wmsInReceiptTaskPage.setWmsInReceiptTaskMaterialList(list);

        wmsInReceiptTaskPage.setOwnerType("1");
        wmsInReceiptTaskPage.setOrganization("A04A01");
        wmsInReceiptTaskPage.setSysOrgCode("A04A01");
        wmsInReceiptTaskPage.setOwner("A05");
        wmsInReceiptTaskPage.setCreateBy(personnelMes);

        wmsInReceiptTaskPage.setTaskDate(DateUtil.parseDate(DateUtil.now()));
        wmsInReceiptTaskPage.setOriginalSystem(SystemConstants.MES);
        wmsInReceiptTaskPage.setRequestPerson("MES请求人员");
        wmsInReceiptTaskPage.setOriginalSystem("MES");
        wmsInReceiptTaskPage.setTaskType(vo.getTaskType());
        wmsInReceiptTaskPage.setSiteCode(vo.getSite());
        wmsInReceiptTaskPage.setRemark(vo.getRemark());
        wmsInReceiptTaskPage.setProductLine(vo.getLineName());
        wmsInReceiptTaskPage.setTaskCode(vo.getTaskCode());
        wmsInReceiptTaskPage.setRequestTime(new Date());
        wmsInReceiptTaskPage.setOriginalSystemNumber(orderCode);
        wmsInReceiptTaskPage.setProductOrderNumber(orderCode);

        if (CollectionUtil.isNotEmpty(wmsInReceiptTaskPage.getWmsInReceiptTaskMaterialList())) {
            Optional<WmsInReceiptTaskMaterial> first = wmsInReceiptTaskPage.getWmsInReceiptTaskMaterialList().stream().filter(t -> StringUtils.isNotBlank(t.getCustomerCode())).findFirst();
            if (first.isPresent()) {
                String customerCode = first.get().getCustomerCode();
                String idByCode = basicCustomerService.getIdByCode(customerCode);
                wmsInReceiptTaskPage.setWmsBasicSupplierId(idByCode);
            }
        }

        // 根据客商编码查询客商id
        if (vo instanceof LaminatedAuxiliaryMaterialReturnRequestVO) {
            LaminatedAuxiliaryMaterialReturnRequestVO vo1 = (LaminatedAuxiliaryMaterialReturnRequestVO) vo;
            String customerCode = vo1.getCustomCode();
            if (StringUtils.isNotBlank(customerCode)) {
                BasicCustomer basicCustomer = iBasicCustomerService.getOne(new LambdaQueryWrapper<BasicCustomer>().eq(BasicCustomer::getCode, customerCode));
                if (ObjectUtil.isNotEmpty(basicCustomer)) {
                    wmsInReceiptTaskPage.setWmsBasicSupplierId(basicCustomer.getId());
                }
            }
            wmsInReceiptTaskPage.setAskRange(vo1.getAskRange());
            wmsInReceiptTaskPage.setUnitsNumber(vo1.getTableQuantity().toPlainString());
        }

        if (vo instanceof FinishedProductWarehousingScaleRequestVO) {
            FinishedProductWarehousingScaleRequestVO vo1 = (FinishedProductWarehousingScaleRequestVO) vo;
            wmsInReceiptTaskPage.setStackNumber(vo1.getPalletCode());
            wmsInReceiptTaskPage.setOrderType(vo1.getIronType());
        }
        if (vo instanceof FinishedProductWarehousingIronRequestVO) {
            FinishedProductWarehousingIronRequestVO vo1 = (FinishedProductWarehousingIronRequestVO) vo;
            wmsInReceiptTaskPage.setOrderType(vo1.getIronType());
            List<FinishedProductWarehousingIronRequestVO.Detail> details = vo1.getDetail();
            Optional<FinishedProductWarehousingIronRequestVO.Detail> first = details.stream().filter(t -> StringUtils.isNotBlank(t.getCustomCode())).findFirst();
            if (first.isPresent()) {
                String customerCode = first.get().getCustomCode();
                if (StringUtils.isNotBlank(customerCode)) {
                    BasicCustomer basicCustomer = iBasicCustomerService.getOne(new LambdaQueryWrapper<BasicCustomer>().eq(BasicCustomer::getCode, customerCode));
                    if (ObjectUtil.isNotEmpty(basicCustomer)) {
                        wmsInReceiptTaskPage.setWmsBasicSupplierId(basicCustomer.getId());
                    }
                }
            }
        }
        if (vo instanceof LaminationReturnRequestVO) {
            LaminationReturnRequestVO vo1 = (LaminationReturnRequestVO) vo;
            if (ObjectUtil.isNotNull(vo1.getTableQuantity())) {
                wmsInReceiptTaskPage.setUnitsNumber(vo1.getTableQuantity().toString());
            }
            wmsInReceiptTaskPage.setOriginalCallTask(vo1.getOutboundTask());
        }
        // 叠片辅材退料
        if (vo instanceof LaminatedAuxiliaryMaterialReturnRequestVO) {
            LaminatedAuxiliaryMaterialReturnRequestVO requestVO = (LaminatedAuxiliaryMaterialReturnRequestVO) vo;
            wmsInReceiptTaskPage.setAskRange(requestVO.getAskRange());
            wmsInReceiptTaskPage.setUnitsNumber(String.valueOf(requestVO.getTableQuantity()));
        }

        //创建流程
        BaseFlowDto base = new BaseFlowDto();
        base.setDocumentType(documentType);
        base.setCode(code);
        base.setData(wmsInReceiptTaskPage);
        base.setBusinessType(BusinessTypeEnum.document_task.toString());
        workFlowService.commit(base);
        String taskId = base.getInfoId();
        DockTaskRecordMap map = new DockTaskRecordMap();
        map.setTaskId(taskId);
        map.setRecordId(recordId);
        map.setMesTaskCode(vo.getTaskCode());
        map.setSite(vo.getSite());
        dockTaskRecordMapMapper.insert(map);
        updateMesStatus(vo);
    }

    /**
     * 记录发送mds请求信息
     *
     * @param re
     */
    private void record(String taskCode, String re) {
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.MDS);
        sendRecord.setBusinessCode(taskCode);
        sendRecord.setUuid(IdUtil.fastUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(re));
        try {
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(DockDataStatus.SUCCESS.getRemark());
            log.info("辅料成本中心领用接口发送成功");
        } catch (Exception e) {
            log.info("辅料成本中心领用接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
        } finally {
            dockDataSendRecordMapper.insert(sendRecord);
        }
    }

    private <T extends MesBaseRequestVO> void wmsOutReceiptTask(List<WmsOutReceiptTaskMaterial> list, String recordId, String code, String documentType, T vo, String orderCode) {
        WmsOutReceiptTaskPage wmsOutReceiptTaskPage = new WmsOutReceiptTaskPage();
        wmsOutReceiptTaskPage.setDocumentCode(FillRuleUtil.executeRule(OUTBOUND_DOCUMENT_CODE, JSON.parseObject(OUTBOUND_PARAM)).toString());
        wmsOutReceiptTaskPage.setDocumentType(documentType);
        wmsOutReceiptTaskPage.setWmsOutReceiptTaskMaterialList(list);
        wmsOutReceiptTaskPage.setTaskDate(DateUtil.parseDate(DateUtil.now()));

        wmsOutReceiptTaskPage.setOwnerType("1");
        wmsOutReceiptTaskPage.setOrganization("A04A01");
        wmsOutReceiptTaskPage.setSysOrgCode("A04A01");
        wmsOutReceiptTaskPage.setOwner("A05");

        wmsOutReceiptTaskPage.setOriginalSystem(SystemConstants.MES);
        wmsOutReceiptTaskPage.setRequestPerson("MES请求人员");
        wmsOutReceiptTaskPage.setCreateBy(personnelMes);
        wmsOutReceiptTaskPage.setRequestTime(DateUtil.now());

        wmsOutReceiptTaskPage.setTaskDate(new Date());
        wmsOutReceiptTaskPage.setTaskType(vo.getTaskType());
        wmsOutReceiptTaskPage.setSiteCode(vo.getSite());
        wmsOutReceiptTaskPage.setProductLine(vo.getLineName());
        wmsOutReceiptTaskPage.setTaskCode(vo.getTaskCode());
        wmsOutReceiptTaskPage.setProductOrderNumber(orderCode);
        wmsOutReceiptTaskPage.setOriginalSystemNumber(orderCode);
        // 横剪叫料板表头添加数量
        if (vo instanceof TransverseShearCallMaterialPlateRequestVO) {
            TransverseShearCallMaterialPlateRequestVO requestVO = (TransverseShearCallMaterialPlateRequestVO) vo;
            wmsOutReceiptTaskPage.setDownBoardNum(requestVO.getDownNumber());
            wmsOutReceiptTaskPage.setUpBoardNum(requestVO.getUpNumber());
        }
        // 叠片叫料表头添加台数
        if (vo instanceof LaminationCallRequestVO) {
            LaminationCallRequestVO requestVO = (LaminationCallRequestVO) vo;
            wmsOutReceiptTaskPage.setUnitsNumber(String.valueOf(requestVO.getTableQuantity()));
        }
        // 叠片叫辅材料表头添加客户
        if (vo instanceof LaminatedAuxiliaryMaterialOrderingRequestVO) {
            LaminatedAuxiliaryMaterialOrderingRequestVO requestVO = (LaminatedAuxiliaryMaterialOrderingRequestVO) vo;
            wmsOutReceiptTaskPage.setCustomer(requestVO.getCustomCode());
            wmsOutReceiptTaskPage.setUnitsNumber(String.valueOf(requestVO.getTableQuantity()));
            wmsOutReceiptTaskPage.setCallRange(requestVO.getAskRange());
        }
        //创建流程
        BaseFlowDto base = new BaseFlowDto();
        base.setDocumentType(documentType);
        base.setCode(code);
        base.setData(wmsOutReceiptTaskPage);
        base.setBusinessType(BusinessTypeEnum.outbound_task.toString());
        workFlowService.commit(base);
        String taskId = base.getInfoId();
        DockTaskRecordMap map = new DockTaskRecordMap();
        map.setTaskId(taskId);
        map.setRecordId(recordId);
        map.setMesTaskCode(vo.getTaskCode());
        map.setSite(vo.getSite());
        dockTaskRecordMapMapper.insert(map);

        updateMesStatus(vo);
    }

    /**
     * 生成移库单
     *
     * @param list
     * @param recordId
     * @param code
     * @param documentType
     * @param vo
     * @param <T>
     */
    private <T extends MesBaseRequestVO> void wmsMoveReceipt(List<WmsMoveReceiptMaterial> list, String recordId, String code, String documentType, T vo, String orderCode) {
        WmsMoveReceiptPage moveReceiptPage = new WmsMoveReceiptPage();
        moveReceiptPage.setDocumentCode(FillRuleUtil.executeRule(MOVE_DOCUMENT_CODE, JSON.parseObject(MOVE_PARAM)).toString());
        moveReceiptPage.setDocumentType(documentType);
        moveReceiptPage.setWmsMoveReceiptMaterialList(list);
        moveReceiptPage.setBusinessDate(new Date());
        moveReceiptPage.setHasChild(1);

        moveReceiptPage.setOwnerType("1");
        moveReceiptPage.setSysOrgCode("A04A01");
        moveReceiptPage.setOrganization("A04A01");
        moveReceiptPage.setTransferFromOwner("A05");
        moveReceiptPage.setTransferFromDepartment("A04A01");
        moveReceiptPage.setTransferFromWarehouseId(queryWarehouseCode(code003));  // 默认四期纸筒仓
        moveReceiptPage.setOriginalSystem(SystemConstants.MES);
        moveReceiptPage.setCreateBy(personnelMes);
        moveReceiptPage.setProductLine(vo.getLineName());
        moveReceiptPage.setOriginalSystemNumber(orderCode);
        moveReceiptPage.setRequestPerson("MES请求人员");
        moveReceiptPage.setRequestTime(new Date());
        moveReceiptPage.setTaskCode(vo.getTaskCode());
        moveReceiptPage.setSiteCode(vo.getSite());
        moveReceiptPage.setWarehouseKeeper("MES请求人员");
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        moveReceiptPage.setWarehouseKeeper(sysUser.getRealname());

        //创建流程
        BaseFlowDto base = new BaseFlowDto();
        base.setDocumentType(documentType);
        base.setCode(code);
        base.setData(moveReceiptPage);
        base.setBusinessType(BusinessTypeEnum.move_type.toString());
        workFlowService.commit(base);
        String taskId = base.getInfoId();
        DockTaskRecordMap map = new DockTaskRecordMap();
        map.setTaskId(taskId);
        map.setRecordId(recordId);
        map.setMesTaskCode(vo.getTaskCode());
        map.setSite(vo.getSite());
        dockTaskRecordMapMapper.insert(map);

        updateMesStatus(vo);
    }

    private <T extends MesBaseRequestVO> void updateMesStatus(T vo) {
        MesBaseRequestVO requestVO = new MesBaseRequestVO();
        requestVO.setRemark(vo.getRemark());
        requestVO.setTaskCode(vo.getTaskCode());
        requestVO.setOperateTime(new Date());
        requestVO.setTaskStatus(MesStatusEnum.TASK_STARTED.getCode());
        requestVO.setSite(vo.getSite());
        requestVO.setOperateReason(vo.getOperateReason());
        requestVO.setOperatorName(vo.getOperatorName());
//        mesRequestClient.updateStatus(vo.getTaskCode(), requestVO);
    }

    /**
     * commit
     *
     * @param vo
     * @param code
     */
    public void commit(MesBaseRequestVO vo, String code) {
        DockTaskRecordMap map = dockTaskRecordMapMapper.selectOne(new LambdaQueryWrapper<DockTaskRecordMap>()
                .eq(DockTaskRecordMap::getMesTaskCode, vo.getTaskCode()));
        if (ObjectUtil.isEmpty(map)) {
            throw new JeecgBootException("未通过taskCode查询到任务id");
        }
        String taskId = map.getTaskId();
        BaseFlowDto baseFlowDto = new BaseFlowDto();
        baseFlowDto.setInfoId(taskId);
        baseFlowDto.setCode(code);
        workFlowService.commit(baseFlowDto);
    }

    /**
     * 闭关流程
     *
     * @param vo
     */
    public void closeFlow(MesBaseRequestVO vo) {
        DockTaskRecordMap map = dockTaskRecordMapMapper.selectOne(new LambdaQueryWrapper<DockTaskRecordMap>()
                .eq(DockTaskRecordMap::getMesTaskCode, vo.getTaskCode()));
        if (ObjectUtil.isEmpty(map)) {
            throw new JeecgBootException("未通过taskCode查询到任务id");
        }
        String taskId = map.getTaskId();
        BaseFlowDto baseFlowDto = new BaseFlowDto();
        baseFlowDto.setRefuseType(2);
        baseFlowDto.setInfoId(taskId);
        workFlowService.interrupt(baseFlowDto);
    }

    /**
     * 通过批次号查询物料id
     *
     * @param batchCode
     * @return
     */
    private String queryMaterialCodeByBatchCode(String batchCode) {
        List<WmsRepertory> list = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                .eq(WmsRepertory::getBatchCode, batchCode));
        if (CollectionUtil.isEmpty(list)) {
            return "";
        }
        WmsRepertory wmsRepertory = list.get(0);
        return wmsRepertory.getMaterialId();
    }

    private String queryWarehouseCode(String warehouseCode) {
        List<WmsBasicWarehouse> wmsBasicWarehouses = warehouseMapper.selectList(new LambdaQueryWrapper<WmsBasicWarehouse>()
                .eq(WmsBasicWarehouse::getCode, warehouseCode));
        if (CollectionUtil.isEmpty(wmsBasicWarehouses)) {
            return "";
        }
        WmsBasicWarehouse wmsBasicWarehouse = wmsBasicWarehouses.get(0);
        return wmsBasicWarehouse.getId();
    }

}
